
package com.scalar.chiptrack.sales.actions;

import java.util.HashMap;



import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.mail.internet.InternetAddress;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.sales.forms.SendPartNumbersMailForm;
import com.scalar.chiptrack.sales.dao.CustomerDAO;



public class SendPartNumbersMailAction extends ChipTrackAction
{

    public SendPartNumbersMailAction ()
    {

    }

    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
    {

        HashMap info = new HashMap ();
        request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
        HashMap errors = new HashMap ();
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        SendPartNumbersMailForm sendPartNumbersMailForm = ( SendPartNumbersMailForm ) form;
        String customerId = request.getParameter ( "customerId" );
        boolean success = false;
        String action = request.getParameter ( "action" );
        request.setAttribute ( "customerId", customerId );
        //System.out.println(" action   "+action );

        String customerName = null;
        String subject = null;
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        String mimeType = sendPartNumbersMailForm.getAttachMIMEType ();

        if ( ( mimeType == null ) || ( mimeType.trim ().length () == 0 ) )
        {
            mimeType = "PDF";
            sendPartNumbersMailForm.setAttachMIMEType ( "PDF" );
        }


        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/sendPartNumbersMail.do?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }
        String from = user.getEmail ();

        if ( ( action != null ) && ( action.equalsIgnoreCase ( "save" ) ) )
        {
            try
            {
                String to = StringUtils.concatStrings ( sendPartNumbersMailForm.getToUsers (), Mailer.EMAIL_SEPARATOR );
                String cc = StringUtils.concatStrings ( sendPartNumbersMailForm.getCcUsers (), Mailer.EMAIL_SEPARATOR );
                String bcc = StringUtils.concatStrings ( sendPartNumbersMailForm.getBccUsers (), Mailer.EMAIL_SEPARATOR );

                to = Mailer.getNotifiableEmails ( to, false );
                cc = Mailer.getNotifiableEmails ( cc, false );
                bcc = Mailer.getNotifiableEmails ( bcc, false );
                if ( cc == null )
                {
                    sendPartNumbersMailForm.setCcUsers ( null );
                }
                if ( bcc == null )
                {
                    sendPartNumbersMailForm.setBccUsers ( null );
                }

                subject = sendPartNumbersMailForm.getSubject ();

                customerName = CustomerDAO.getCustomerName( null, Integer.parseInt( customerId ) ) ;
                if ( subject == null )
                {
                    subject = "Customer Part Numbers For : " + customerName;

                }
                sendPartNumbersMailForm.setSubject ( subject );
                String message = sendPartNumbersMailForm.getMessage ();

                String host = request.getHeader ( "HOST" );

                String salesAckFile = null;

                if ( "PDF".equalsIgnoreCase ( mimeType ) )
                   salesAckFile = CustomerPartNumbersAction.getPartNumbersAckPDFFile ( host, customerId );
                else
                   salesAckFile = CustomerPartNumbersAction.getPartNumbersAckHTMLFile ( host, customerId );

                String[] mailAttachments = null;


                String isConfirm = ( String ) session.getAttribute ( "isConfirm" );
                String sysAdminEmail = ConfigManager.getSysAdminEmail ();
                String companyEmailId = sysAdminEmail.substring ( sysAdminEmail.indexOf ( "@" ) + 1, sysAdminEmail.length () );
                if ( isConfirm == null )
                {
                    to = Mailer.getNotifiableEmails ( to, false );
                    cc = Mailer.getNotifiableEmails ( cc, false );
                    bcc = Mailer.getNotifiableEmails ( bcc, false );
                    InternetAddress[] toAddress = null;
                    InternetAddress[] ccAddress = null;
                    InternetAddress[] bccAddress = null;

                    String emailIds = "";
                    if ( to != null )
                    {
                        toAddress = InternetAddress.parse ( to );
                        for ( int i = 0; i < toAddress.length; i++ )
                        {
                            InternetAddress temp = toAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if(emailIds == "" )
                                {
                                emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                 emailIds = emailIds +", "+ temp.getAddress () ;
                                }
                            }
                        }
                    }
                    if ( cc != null )
                    {
                        ccAddress = InternetAddress.parse ( cc );
                        for ( int i = 0; i < ccAddress.length; i++ )
                        {
                            InternetAddress temp = ccAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if(emailIds == "" )
                                {
                                    emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                    emailIds = emailIds +", "+ temp.getAddress () ;
                                }

                            }
                        }
                    }
                    if ( bcc != null )
                    {
                        bccAddress = InternetAddress.parse ( bcc );
                        for ( int i = 0; i < bccAddress.length; i++ )
                        {
                            InternetAddress temp = bccAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if(emailIds == "" )
                                {
                                    emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                    emailIds = emailIds +", "+ temp.getAddress () ;
                                }
                            }
                        }
                    }

                    if ( emailIds.trim ().length () > 0 )
                    {
                        errors.put ( "The following e-mails are going out of the company. Please confirm to send them.", null );
                        info.put ( "Emails ", emailIds );

                        session.setAttribute ( "isConfirm", "True" );
                        return mapping.findForward ( "success" );
                    }

                }
                mailAttachments = new String[]{salesAckFile};
                Mailer.send ( from, to, cc, bcc, subject, message, mailAttachments, Mailer.CONTENT_TYPE_HTML, false );
                info.put ( "Email has been sent successfully", null );
                session.removeAttribute ( "ShowAgain" );
                session.removeAttribute ( "isConfirm" );
            }
            catch ( Exception se )
            {
                success = false;
                String errMessage = "Error";

                errors.put ( errMessage, "Could not send Email. Please check the EmailId" );
                se.printStackTrace ();
                return mapping.findForward ( "success" );
            }//catch

            return ( mapping.findForward ( "sendPartNumbersMailView" ) );
        }//if

        try
        {

            subject = sendPartNumbersMailForm.getSubject ();
            customerName = CustomerDAO.getCustomerName(null, Integer.parseInt( customerId ) ) ;
            if ( subject == null )
            {
                subject = "Customer Part Numbers For  " + customerName;
            }
            sendPartNumbersMailForm.setSubject ( subject );
        }

        catch ( Exception se )
        {
            System.out.println ( "Exception while loading Customer Part Number emails.. "+se );
        }

        session.removeAttribute ( "ShowAgain" );
        session.removeAttribute ( "isConfirm" );


        request.setAttribute ( "sendPartNumbersMailForm", sendPartNumbersMailForm);
        return ( mapping.findForward ( "success" ) );
    }
}